package com.google.code.sysarch.v4.graphical;

import org.lwjgl.opengl.GL11;

import com.google.code.sysarch.v4.vrml_loader.VRML_Model;

public class Ship {

	public static final float SINK_ROTATION_SPEED = 12f;
	public static final float SINK_SPEED = 3.5f;	
	public static final float[] MAX_SINK_ROTATION = { 0, 0, 30, 60, 60 };
	
	private VRML_Model model;
	private int grid_x, grid_y;
	private int length;
	private int orientation;
	private float sinkrot;
	private float sinkdepth;
	private float sinkoffset;
	private boolean sinking;
	private float x, y, z;
	private float rotx, roty, rotz;
	private int name;
	
	Ship(VRML_Model model, int gx, int gy, int length, int orientation) {
		this.model = model;
		this.grid_x = gx;
		this.grid_y = gy;
		this.length = length;
		this.orientation = orientation;
		this.sinking = false;
	}
	
	public VRML_Model getModel() {
		return this.model;
	}
	
	public void setModel(VRML_Model model) {
		this.model = model;
	}
	
	public void setGridCoords(int x, int y) {
		this.grid_x = x;
		this.grid_y = y;
	}
	
	public void setLength(int length) {
		this.length = length;
	}
	
	public void setOrientation(int or) {
		this.orientation = or;
	}
	
	public int getX() {
		return this.grid_x;
	}
	
	public int getY() {
		return this.grid_y;
	}
	
	public int getLength() {
		return this.length;
	}
	
	public int getOrientation() {
		return this.orientation;
	}
	
	public void setName(int name) {
		this.name = name;
	}
	
	public int getName() {
		return this.name;
	}
	
	public void translate(float x, float y, float z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}
	
	public void rotate(float x, float y, float z) {
		this.rotx = x;
		this.roty = y;
		this.rotz = z;
	}
	
	public void sink() {
		this.sinking = true;
		this.sinkdepth = 0;
		this.sinkrot = 0;
	}
	
	public void update(double delta, float gridsize) {
		if (this.sinking) {
			if (this.sinkrot <= MAX_SINK_ROTATION[this.length-1]-1) {
				this.sinkrot += SINK_ROTATION_SPEED * delta;
				if (this.sinkrot > MAX_SINK_ROTATION[this.length-1]-1) this.sinkrot = MAX_SINK_ROTATION[this.length-1];
				float angle = (float) (this.sinkrot * Math.PI) / 180f;
				float len = gridsize * ((this.length/2f) - 0.5f);
				this.sinkdepth = (float)(Math.sin(angle) * len) / 2;
				this.sinkoffset = (float)(len * (1 - Math.cos(angle)));
			} else {
				sinkdepth -= SINK_SPEED * delta;
			}
		}
	}
	
	public void render() {
		if (this.sinking) {
			this.y = sinkdepth;
			this.rotx = this.sinkrot;
			if (this.orientation == Grid.ORIENTATION_X) {
				this.x += this.sinkoffset;
			} else if (this.orientation == Grid.ORIENTATION_Y) {
				this.z += this.sinkoffset;
			}
		}
		GL11.glPushMatrix();	
			GL11.glTranslatef(x, y, z);		
			GL11.glRotatef(roty, 0, 1, 0);
			GL11.glRotatef(rotx, 1, 0, 0);
			GL11.glRotatef(rotz, 0, 0, 1);
			model.render();
		GL11.glPopMatrix();
	}
	
}
